// pages/shopnavigate/shopnavigate.js

// 引入SDK核心类

/**/

var amapFile = require('../../libs/amap-wx.js');
let amap = require("../../libs/amap.js");

var myAmapFun = new amapFile.AMapWX({

  key: '1336bfc7fd9f11ec452d1d4f0cab4c8c' // 必填 换成自己申请到的

});


Page({

  /**
   * 页面的初始数据
   */
  data: {
    mapheight:'90vh',
    selectIndex:null,
    list:[{
      id:1,
      imgUrl:'bus',
      name:'公交'
    },{
      id: 2,
      imgUrl: 'drive',
      name: '自驾'
    },{
      id: 3,
      imgUrl: 'riding',
      name: '骑行'
    }, {
      id: 4,
      imgUrl: 'walk',
      name: '步行'
    }],
    jd: null,//当前的经纬度
    wd: null,
    origin:null,
    destination:null,
    stroe_location:'',
    city:'',
    distance:null,
    cost:null,
    controls:[],
    markers:[],
    polyline: [],
    points: [],
    detailHidden: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;

  //  用户当前的位置
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res.latitude, res.longitude, '当前位置经纬度')
        var latitude1 = res.latitude;
        var longitude1 = res.longitude;
        var mapcenter = [latitude1, longitude1];
        
        let origin = `${longitude1},${latitude1}`;//起点

        that.setData({
          origin: origin,
          wd: latitude1,
          jd: longitude1,
          points: [{
            longitude: res.longitude,
            latitude: res.latitude
          }],

        }) 
      }
    })
   
  //  目的地的位置
    var obj = JSON.parse(options.storeInfo);
    console.log('目的地', obj);
    this.setData({
      stroe_location: obj
    })
   
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    var that = this;
  
  },
  positionTap: function (e) {

    var index = e.currentTarget.dataset.index;
    console.log(index);
    if (this.data.selectIndex == index)return;

    this.setData({
      selectIndex: index
    })

    var that = this;

    switch (index) {
      case 0:
        myAmapFun.getTransitRoute(this.getBusData('#008B8B'));
        break;
      case 1:
        
        myAmapFun.getDrivingRoute(this.getDataObj('#4B0082'));
        break;
      case 2:
        myAmapFun.getRidingRoute(this.getDataObj('#00FFFF'));
        break;
      case 3:
        myAmapFun.getWalkingRoute(this.getDataObj());
        break;
      default:
        return;
    }
    that.setData({
      detailHidden: false,
      mapheight:'75vh'
    })
  },
  getDataObj:function(color){
    var _this = this;
    var color = color || "#0091ff";

    return {
      origin: _this.data.points[0].longitude + ',' + _this.data.points[0].latitude,
      destination: _this.data.points[1].longitude + ',' + _this.data.points[1].latitude,
      success(data) {
        console.log(data,'其他路线');
        var points = [];
        if (!data.paths || !data.paths[0] || !data.paths[0].steps) {
          wx.showToast({ title: '失败！' });
          return;
        }
        if (data.paths && data.paths[0] && data.paths[0].steps) {
          var steps = data.paths[0].steps;
          for (var i = 0; i < steps.length; i++) {
            var poLen = steps[i].polyline.split(';');
            for (var j = 0; j < poLen.length; j++) {
              points.push({
                longitude: parseFloat(poLen[j].split(',')[0]),
                latitude: parseFloat(poLen[j].split(',')[1])
              })
            }
          }
        }
        _this.setData({
          distance: data.paths[0].distance,
          cost: parseInt(data.paths[0].duration / 60),
          polyline: [{
            points: points,
            color: color,
            width: 6
          }]
        });
      },
      fail(info) {
        wx.showToast({ title: '失败！' })
      }
    }
  } ,
  getBusData: function (color){
    var _this = this;
    var color = color || "#0091ff";

    return {
      origin: _this.data.points[0].longitude + ',' + _this.data.points[0].latitude,
      destination: _this.data.points[1].longitude + ',' + _this.data.points[1].latitude,
      city: _this.data.city,
      success(data) {
        console.log(data,'bus');
        var points = [], cost = 0;
        if (data && data.transits) {
          var transits = data.transits;
          for (var i = 0; i < transits.length; i++) {
            cost += parseInt(transits[i].duration);
            
            var segments = transits[i].segments;

            for (var j = 0; j < segments.length; j++) {
              if (segments[j].bus.buslines[0] && segments[j].bus.buslines[0].polyline) {
                var steps = segments[j].bus.buslines[0].polyline.split(';');
                for (var k = 0; k < steps.length; k++) {
                  var point = steps[k].split(',');
                  points.push({
                    longitude: point[0],
                    latitude: point[1]
                  })
                }
                  console.log(points);

                  //在公交站点
                  if (parseInt(point[0] * 10000) === parseInt(_this.data.points[1].longitude * 10000) && parseInt(point[1] * 10000) === parseInt(_this.data.points[1].latitude * 10000)) { 
                    _this.setData({
                      distance: data.distance,
                      cost: parseInt(cost / 60),
                      polyline: [
                        {
                          points: points,
                          color: color,
                          width: 6
                        }]
                    });
                   }else{
                     //不在公交站点（处理）
                     //起点处理
                     var obj1 = _this.data.points[0];
                     var obj2 = points[0];

                     var points_s = [obj1,obj2];
                     
                     //终点处理
                    var obj3 = _this.data.points[1];
                    var obj4 = points[points.length - 1];

                    var points_e = [obj3, obj4];


                    _this.setData({
                      distance: data.distance,
                      cost: parseInt(cost / 60),

                      polyline: [
                        {
                          points: points_s,
                          color: '#95477F',
                          width: 6,
                          dottedLine: true
                        },
                        {
                          points: points,
                          color: color,
                          width: 6
                        },
                        {
                          points: points_e,
                          color: '#95477F',
                          width: 6,
                          dottedLine: true
                        }]
                    });
                   }
                                  
                    return;

              }
            }
          }
        }
      },
      fail(info) {
        wx.showToast({ title: '失败！' })
      }
    }
  },


  makertap:function(){

  },
  clickcontrol:function(){

  },
  mapchange:function(){

  },
  goDetail:function(){
    wx.openLocation({
      latitude: parseFloat(this.data.markers[1].latitude) ,
      longitude: parseFloat(this.data.markers[1].longitude),
      name: this.data.stroe_location.name,
      scale: 28
    })  
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
    var that = this;
    // 店铺的经纬度
    var longitude = this.data.stroe_location.lng;
    var latitude = this.data.stroe_location.lat;
    var name = this.data.stroe_location.name;
    var address = this.data.stroe_location.address;

    that.setData({
      city: address,
    })
    //逆地理编码

    setTimeout(function () { 

      let destination = `${longitude},${latitude}`;
      that.setData({
        destination: destination
      })

      var obj1 = {
        iconPath: "../../images/mapicon_navi_s.png",
        id: 0,
        latitude: that.data.wd,
        longitude: that.data.jd,
        width: 23,
        height: 33
      }
      var obj2 = {
        iconPath: "../../images/mapicon_navi_e.png",
        id: 1,
        latitude: latitude,
        longitude: longitude,
        width: 23,
        height: 33
      }
      var marks = [obj1, obj2];

      var points = that.data.points;

      points.push({
        longitude: longitude,
        latitude: latitude
      })

      that.setData({
        markers: marks,
        points: points

      })
      console.log(marks, 'markers');
    }, 1500);

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})
// https://blog.csdn.net/haibo0668/article/details/80693265
// https://blog.csdn.net/u011330225/article/details/75209877
// https://blog.csdn.net/zzwwjjdj1/article/details/79425220
//https://blog.csdn.net/m0_38082783/article/details/79287428